package com.uziot.bucket.poi.office.excel;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;

import java.io.*;
import java.util.UUID;

/**
 * @author shidt
 * @version V1.0
 * @className Excel2PdfUtil
 * @date 2020-07-10 23:53:04
 * @description 表格转换为PDF
 */

public class Excel2PdfUtil {
    public static void main(String[] args) {
        //new com.aspose.cells.License().setLicense();
        Excel2PdfUtil.excel2pdf("C:\\Users\\detao\\Desktop\\cc.xls", "C:\\Users\\detao\\Desktop\\");
    }

    /**
     * excel文件转换为PDF文件
     *
     * @param address    需要转化的Excel文件地址，
     * @param outputPath 转换后的文件地址
     */
    public static String excel2pdf(String address, String outputPath) {
        String fileName = UUID.randomUUID() + ".pdf";
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return null;
        }
        try {
            FileWriter writer = new FileWriter(outputPath + fileName);
            writer.close();
            // 输出路径
            File pdfFile = new File(outputPath + fileName);
            FileInputStream fileInputStream = new FileInputStream(address);
            // excel路径，这里是先把数据放进缓存表里，然后把缓存表转化成PDF
            Workbook wb = new Workbook(fileInputStream);
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            //参数true把内容放在一张PDF页面上；
            pdfSaveOptions.setOnePagePerSheet(true);
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 获取认证，去除水印
     *
     * @return 是否成功
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            //这个文件应该是类似于密码验证(证书？)，用于获得去除水印的权限
            InputStream is = Excel2PdfUtil.class.getClassLoader().getResourceAsStream("/static/license.xml");
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}